/* global window */

import { history } from 'umi'
import { stringify } from 'qs'
import store from 'store'
const { pathToRegexp } = require("path-to-regexp")
import { ROLE_TYPE } from 'utils/constant'
import { queryLayout } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import config from 'config'
import {request} from "../utils";

const { queryRouteList, logoutUser, queryUserInfo,myNotification,readNotifications,readAllNotifications,querySelfUserDetails,updateSelfUser } = api

const goDashboard = () => {
  if (pathToRegexp(['/', '/login']).exec(window.location.pathname)) {
    history.push({
      pathname: '/dashboard',
    })
  }
}

export default {
  namespace: 'app',
  state: {
    routeList: [
      {
        id: '1',
        icon: 'laptop',
        name: 'Dashboard',
        zhName: '仪表盘',
        router: '/dashboard',
      },
    ],
    locationPathname: '',
    locationQuery: {},
    theme: store.get('theme') || 'light',
    collapsed: store.get('collapsed') || false,
    notifications: [
    ],
    notification: {title:'', content: ''},
    notificationVisible: false
  },
  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'query' })
      dispatch({ type: 'queryNotification' })
    },
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        })
      })
    },

    setupRequestCancel({ history }) {
      history.listen(() => {
        const { cancelRequest = new Map() } = window

        cancelRequest.forEach((value, key) => {
          if (value.pathname !== window.location.pathname) {
            value.cancel(CANCEL_REQUEST_MESSAGE)
            cancelRequest.delete(key)
          }
        })
      })
    },
  },
  effects: {
    *query({ payload }, { call, put, select }) {
      // store isInit to prevent query trigger by refresh
      const isInit = store.get('isInit')
      if (isInit) {
        goDashboard()
        return
      }
      const { locationPathname } = yield select(_ => _.app)
      try {
        const userInfo = yield call(queryUserInfo, payload)
        //TODO 统一处理业务层code
        if (userInfo.success && userInfo.code == 2000) {
          const user = userInfo.payload
          const { list } = yield call(queryRouteList)
          const { permissions } = user
          let routeList = list
          if (
            true || // 服务器端已经处理 返回的路由全部显示
            permissions.role === ROLE_TYPE.ADMIN ||
            permissions.role === ROLE_TYPE.DEVELOPER
          ) {
            permissions.visit = list.map(item => {
              if(item.visible) {
                return item.id
              }
            })
          } else {
            routeList = list.filter(item => {
              const cases = [
                permissions.visit.includes(item.id),
                item.mpid
                  ? permissions.visit.includes(item.mpid) || item.mpid === '-1'
                  : true,
                item.bpid ? permissions.visit.includes(item.bpid) : true,
              ]
              return cases.every(_ => _)
            })
          }
          store.set('routeList', routeList)
          store.set('permissions', permissions)
          store.set('user', user)
          store.set('isInit', true)

          goDashboard()
        } else if (queryLayout(config.layouts, locationPathname) !== 'public') {
          history.push({
            pathname: '/login',
            search: stringify({
              from: locationPathname,
            }),
          })
        }
      } catch (e) {
        if(e.statusCode == 401) {
          history.push({
            pathname: '/login',
            search: stringify({
              from: locationPathname,
            }),
          })
        }
      }


    },

    //查询通知相关信息
    *queryNotification({ payload }, { call, put, select }) {
      const data = yield call(myNotification,{});
      if(data.success) {
        yield put({
          type: 'updateState',
          payload: {
            notifications: data.payload.list
          },
        })
      }
    },

    //查询当前用户信息
    *queryMyselfInfo({},{call,put}) {
      const data = yield call(querySelfUserDetails,{});
      if(data.success) {
        return data.payload;
      }
      return null
    },
    //编辑管理用户个人信息
    *updateSelfUser({payload}, {call,put}) {
      const data = yield  call(updateSelfUser, payload);
      return true;
    },

    *signOut({ payload }, { call, put }) {
      store.each(function(value, key) {
        store.remove(key)
      })
      yield put({ type: 'query' })
    },
    //全部消息已读
    *allNotificationsRead({payload}, {call}) {
      // state.notifications = []
      yield call(readAllNotifications)
    },
    //指定消息已读
    *notificationsRead({payload}, {call,put}) {
      yield call(readNotifications, {ids: payload.id});
      yield put({
        type: 'updateState',
        payload: {notificationVisible: false}
      });
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },

    //显示系统消息
    handleShowNotification(state, {payload}) {
      return {
        ...state,
        ...payload,
      }
    },

    handleThemeChange(state, { payload }) {
      store.set('theme', payload)
      state.theme = payload
    },

    handleCollapseChange(state, { payload }) {
      store.set('collapsed', payload)
      state.collapsed = payload
    },
  },
}
